<?php 
defined('IN_DESTOON') or exit('Access Denied');
require DT_ROOT.'/module/'.$module.'/common.inc.php';
$MG['buy_limit'] > -1 or dalert(lang('message->without_permission_and_upgrade'), 'goback');
require DT_ROOT.'/include/post.func.php';
include load($module.'.lang');
include load('my.lang');
require MD_ROOT.'/buy.class.php';
$do = new buy($moduleid);
if(in_array($action, array('add', 'edit'))) {
	$FD = cache_read('fields-'.substr($table, strlen($DT_PRE)).'.php');
	if($FD) require DT_ROOT.'/include/fields.func.php';
	isset($post_fields) or $post_fields = array();
	$CP = $MOD['cat_property'];
	if($CP) require DT_ROOT.'/include/property.func.php';
	isset($post_ppt) or $post_ppt = array();
}
$sql = $_userid ? "username='$_username'" : "ip='$DT_IP'";
$limit_used = $limit_free = $need_password = $need_captcha = $need_question = $fee_add = 0;
if(in_array($action, array('', 'add'))) {
	$r = $db->get_one("SELECT COUNT(*) AS num FROM {$table} WHERE $sql AND status>1");
	$limit_used = $r['num'];
	$limit_free = $MG['buy_limit'] > $limit_used ? $MG['buy_limit'] - $limit_used : 0;
}
if(check_group($_groupid, $MOD['group_refresh'])) $MOD['credit_refresh'] = 0;

switch($action) {
	case 'add':
		if($MG['buy_limit'] && $limit_used >= $MG['buy_limit']) dalert(lang($L['info_limit'], array($MG[$MOD['module'].'_limit'], $limit_used)), $_userid ? $MODULE[2]['linkurl'].$DT['file_my'].'?mid='.$mid : $MODULE[2]['linkurl'].$DT['file_my']);
		if($MG['day_limit']) {
			$today = $today_endtime - 86400;
			$r = $db->get_one("SELECT COUNT(*) AS num FROM {$table} WHERE $sql AND addtime>$today");
			if($r && $r['num'] >= $MG['day_limit']) dalert(lang($L['day_limit'], array($MG['day_limit'])), $_userid ? $MODULE[2]['linkurl'].$DT['file_my'].'?mid='.$mid : $MODULE[2]['linkurl'].$DT['file_my']);
		}

		if($MG['buy_free_limit'] >= 0) {
			$fee_add = ($MOD['fee_add'] && (!$MOD['fee_mode'] || !$MG['fee_mode']) && $limit_used >= $MG['buy_free_limit'] && $_userid) ? dround($MOD['fee_add']) : 0;
		} else {
			$fee_add = 0;
		}
		$fee_currency = $MOD['fee_currency'];
		$fee_unit = $fee_currency == 'money' ? $DT['money_unit'] : $DT['credit_unit'];
		$need_password = $fee_add && $fee_currency == 'money';
		$need_captcha = $MOD['captcha_add'] == 2 ? $MG['captcha'] : $MOD['captcha_add'];
		$need_question = $MOD['question_add'] == 2 ? $MG['question'] : $MOD['question_add'];
		$could_color = check_group($_groupid, $MOD['group_color']) && $MOD['credit_color'] && $_userid;

		if($submit) {
			if($fee_add && $fee_add > ($fee_currency == 'money' ? $_money : $_credit)) dalert($L['balance_lack']);
			if($need_password && !is_payword($_username, $password)) dalert($L['error_payword']);
                        if($post['price']==""||!is_numeric($post['price'])){
                          dalert('输入采购交易金额只能为整数或者小数');
                         }
			if(!$_userid) {
				if(strlen($post['company']) < 4) dalert($L['type_company']);
				if($AREA) {
					if(!isset($AREA[$post['areaid']])) dalert($L['type_area']);
				} else {
					if(!$post['areaid']) dalert($L['type_area']);
				}
				if(strlen($post['truename']) < 4) dalert($L['type_truename']);
				if(strlen($post['mobile']) < 7) dalert($L['type_mobile']);
			}

			if($MG['add_limit']) {
				$last = $db->get_one("SELECT addtime FROM {$table} WHERE $sql ORDER BY itemid DESC");
				if($last && $DT_TIME - $last['addtime'] < $MG['add_limit']) dalert(lang($L['add_limit'], array($MG['add_limit'])));
			}
			$msg = captcha($captcha, $need_captcha, true);
			if($msg) dalert($msg);
			$msg = question($answer, $need_question, true);
			if($msg) dalert($msg);

			if($do->pass($post)) {
                          
				$CAT = get_cat($post['catid']);
				if(!$CAT || !check_group($_groupid, $CAT['group_add'])) dalert(lang($L['group_add'], array($CAT['catname'])));
				$post['addtime'] = $post['level'] = $post['fee'] = 0;
				$post['style'] = $post['template'] = $post['note'] = $post['filepath'] = '';
				if(!$IMVIP && $MG['uploadpt']) $post['thumb1'] = $post['thumb2'] = '';
				$need_check =  $MOD['check_add'] == 2 ? $MG['check'] : $MOD['check_add'];
				$post['status'] = 5;
				$post['hits'] = 0;
				$post['username'] = $_username;
				$post['company_id'] = $_userid; 
				if($could_color && $color && $_credit > $MOD['credit_color']) {
					$post['style'] = $color;
					credit_add($_username, -$MOD['credit_color']);
					credit_record($_username, -$MOD['credit_color'], 'system', $L['title_color'], '['.$MOD['name'].']'.$post['title']);
				}
				if($FD) fields_check($post_fields);
            			if($CP) property_check($post_ppt);
                               
				$do->add($post);
				if($FD) fields_update($post_fields, $table, $do->itemid);
				if($CP) property_update($post_ppt, $moduleid, $post['catid'], $do->itemid);
				if($MOD['show_html'] && $post['status'] > 2) $do->tohtml($do->itemid);

				if($fee_add) {
					if($fee_currency == 'money') {
						money_add($_username, -$fee_add);
						money_record($_username, -$fee_add, $L['in_site'], 'system', lang($L['credit_record_add'], array($MOD['name'])), 'ID:'.$do->itemid);
					} else {
						credit_add($_username, -$fee_add);
						credit_record($_username, -$fee_add, 'system', lang($L['credit_record_add'], array($MOD['name'])), 'ID:'.$do->itemid);
					}
				}
				
				$msg = $post['status'] == 2 ? $L['success_check'] : $L['success_add'];
				$js = '';
				if(isset($post['sync_sina']) && $post['sync_sina']) $js .= sync_weibo('sina', $moduleid, $do->itemid);
				if(isset($post['sync_qq']) && $post['sync_qq']) $js .= sync_weibo('qq', $moduleid, $do->itemid);
				if($_userid) {
					set_cookie('dmsg', $msg);
					$forward = $MODULE[2]['linkurl'].$DT['file_my'].'?mid='.$mid.'&status='.$post['status'];
					$msg = '';
				} else {
					$forward = $MODULE[2]['linkurl'].$DT['file_my'].'?mid='.$mid.'&action=add';
				}
				$js .= 'window.onload=function(){parent.window.location="'.$forward.'";}';
                               
				dalert($msg, '', $js);
			} else {
				dalert($do->errmsg, '', ($need_captcha ? reload_captcha() : '').($need_question ? reload_question() : ''));
			}
		} else {
			if($itemid) {
				$MG['copy'] && $_userid or dalert(lang('message->without_permission_and_upgrade'), 'goback');

				$do->itemid = $itemid;
				$item = $do->get_one();
				if(!$item || $item['username'] != $_username) message();
				extract($item);
				$thumb = $thumb1 = $thumb2 = '';
				$totime = $totime > $DT_TIME ? timetodate($totime, 3) : '';
			} else {
				foreach($do->fields as $v) {
					$$v = '';
				}
				$content = '';
				$catid = 0;
				$totime = '';
				$typeid = 0;
			}
			$item = array();
		}
	break;
	case 'edit':
		$itemid or message();
		$do->itemid = $itemid;
		$item = $do->get_one();
		if(!$item || $item['username'] != $_username) message();

		if($MG['edit_limit'] < 0) message($L['edit_refuse']);
		if($MG['edit_limit'] && $DT_TIME - $item['addtime'] > $MG['edit_limit']*86400) message(lang($L['edit_limit'], array($MG['edit_limit'])));

		if($submit) {
			if($do->pass($post)) {
				$CAT = get_cat($post['catid']);
				if(!$CAT || !check_group($_groupid, $CAT['group_add'])) dalert(lang($L['group_add'], array($CAT['catname'])));
				$post['addtime'] = timetodate($item['addtime']);
				$post['level'] = $item['level'];
				$post['fee'] = $item['fee'];
				$post['style'] = $item['style'];
				$post['template'] = $item['template'];
				$post['filepath'] = $item['filepath'];
				$post['note'] = $item['note'];
				if(!$IMVIP && $MG['uploadpt']) {
					$post['thumb1'] = $item['thumb1'];
					$post['thumb2'] = $item['thumb2'];
				}
				$need_check =  $MOD['check_add'] == 2 ? $MG['check'] : $MOD['check_add'];
				$post['status'] = $item['status'];
				$post['hits'] = $item['hits'];
				$post['username'] = $_username;
				if($FD) fields_check($post_fields);
				if($CP) property_check($post_ppt);
				if($FD) fields_update($post_fields, $table, $do->itemid);
				if($CP) property_update($post_ppt, $moduleid, $post['catid'], $do->itemid);
				$do->edit($post);
				set_cookie('dmsg', $L['success_edit']);
				dalert('', '', 'parent.window.location="'.$forward.'"');
			} else {
				dalert($do->errmsg);
			}
		} else {
			extract($item);
			$totime = $totime ? timetodate($totime, 3) : '';
		}
	break;
        case "purchase":
        
            $itemid = $_REQUEST['itemid'];
            $catid = $_REQUEST['catid'];
            $buy = $db->get_one("SELECT * FROM {$DT_PRE}buy_6 WHERE itemid=$itemid and catid =$catid");
            if(!empty($buy)){
                $user_id = $buy['company_id'];
                $userinfo = $db->get_one("SELECT userid,username,bank,money,locking,money+locking as total FROM {$DT_PRE}member WHERE userid=$user_id");
            }
          
            if(isset($_REQUEST['flag'])&&$_REQUEST['flag']==2){
        
                 if(empty($userinfo)||$userinfo['total']<$buy['price']){
                     echo json_encode(1);exit;
                 }else if($buy['status']==0||$buy['status']==3||$buy['status']==5){
                      if($userinfo['locking']>=$buy['price']){
                         $money = 0; 
                         $locking = $userinfo['locking']-$buy['price'];
                      }else{
                          $locking = 0;
                          $money = -($buy['price']-$userinfo['locking']);
                      }
                      $result =  $db->query("UPDATE {$DT_PRE}buy_6 SET status=2 WHERE itemid=$itemid");
                      if($result){//这里后面需要修改为事务，现在没时间
                           $result2 = $db->query("UPDATE {$DT_PRE}member SET money=money+$money,locking=locking=+$locking WHERE userid=$user_id");
                           //流水记录
                           $userinfo = $db->get_one("SELECT userid,username,bank,money,locking,money+locking as total FROM {$DT_PRE}member WHERE userid=$user_id");
                           if($result2){
                               $username = $userinfo['username'];
                               $bank = $userinfo['bank'];
                               $amount = -$buy['price'];
                               $balance = $userinfo['money'];
                               $reason = '发布求购-'.$buy['title'];
                               $note = '发布求购-'.$buy['note'];
                               $editor = $userinfo['username'];
                               $db->query("INSERT INTO {$DT_PRE}finance_record (username,bank,amount,balance,addtime,reason,note,editor) VALUES ('$username','$bank','$amount','$balance','$DT_TIME','$reason','$note','$editor')");
                               echo json_encode(8);exit;
                           }else{
                               $db->query("UPDATE {$DT_PRE}buy_6 SET status=3 WHERE itemid=$itemid");
                               echo json_encode(3);exit;
                           }
                           
                      }
                 }else{
                     echo json_encode(2);exit;
                 }
            }
        
           // var_dump($buy);
            $head_title = lang($L['module_manage'], array($MOD['name']));
            include template($MOD['template_my'] ? $MOD['template_my'] : 'my_'.$action, 'member');
            exit;
        break;
	case 'delete':
            
		$MG['delete'] or message();
		$itemid or message();
		$itemids = is_array($itemid) ? $itemid : array($itemid);
		foreach($itemids as $itemid) {
			$do->itemid = $itemid;
			$item = $db->get_one("SELECT username FROM {$table} WHERE itemid=$itemid");
			if(!$item || $item['username'] != $_username) message();
			$do->recycle($itemid);
		}
		dmsg($L['success_delete'], $forward);
	break;
	case 'refresh':
        
		$MG['refresh_limit'] > -1 or dalert(lang('message->without_permission_and_upgrade'), 'goback');
		$do->_update($_username);
		$itemid or message($L['select_info']);
		$itemids = $itemid;
		$s = $f = 0;
		foreach($itemids as $itemid) {
			$do->itemid = $itemid;
			$item = $db->get_one("SELECT username,edittime FROM {$table} WHERE itemid=$itemid");
			$could_refresh = $item && $item['username'] == $_username;
			if($could_refresh && $MG['refresh_limit'] && $DT_TIME - $item['edittime'] < $MG['refresh_limit']) $could_refresh = false;
			if($could_refresh && $MOD['credit_refresh'] && $MOD['credit_refresh'] > $_credit) $could_refresh = false;
			if($could_refresh) {
				$do->refresh($itemid);
				$s++;
				if($MOD['credit_refresh']) $_credit = $_credit - $MOD['credit_refresh'];
			} else {
				$f++;
			}			
		}
		if($MOD['credit_refresh'] && $s) {
			$credit = $s*$MOD['credit_refresh'];
			credit_add($_username, -$credit);
			credit_record($_username, -$credit, 'system', lang($L['credit_record_refresh'], array($MOD['name'])), lang($L['refresh_total'], array($s)));
		}
		$msg = lang($L['refresh_success'], array($s));
		if($f) $msg = $msg.' '.lang($L['refresh_fail'], array($f));
		dmsg($msg, $forward);
	break;
        case 'tongguo' :
            $s_status = $_REQUEST['s_status'];
            if(!empty($s_status)){
                $s_status = $s_status + 8;
            }
            if($s_status==9){//打钱
                $res = $db->get_one("SELECT a.company_id srcid,a.price srcprice,b.company_id destid,b.price destprice FROM {$DT_PRE}buy_6 a, {$DT_PRE}purchase_price b WHERE a.purchase_price_id=b.id AND a.status=8 AND a.purchase_price_id > 0  AND a.itemid=$itemid");
                if(!empty($res)&&!empty($res['srcid'])&&!empty($res['destid'])){
                    if($res['srcprice']>=$res['destprice']){
                        $cha = $res['srcprice'] - $res['destprice'];
                        $db->query("update {$DT_PRE}member set money = money+{$cha} where  userid =  ".$res['srcid']);
                        $db->query("update {$DT_PRE}member set money = money+{$res['destprice']} where  userid =  ".$res['destid']);
                        $result = $db->query("update $table set status = {$s_status} where  itemid = {$itemid}");
                        //流水
                         $src_r = $db->get_one("select * from {$DT_PRE}member where userid=".$res['srcid']);
                         $des_r = $db->get_one("select * from {$DT_PRE}member where userid=".$res['destid']);
                               $username = $src_r['username'];
                               $bank = $src_r['bank'];
                               $amount = $cha;
                               $balance = $src_r['money'];
                               $reason = '采购报价多余盈利';
                               $note = '采购报价多余盈利'.$cha;
                               $editor = $src_r['username'];
                               $db->query("INSERT INTO {$DT_PRE}finance_record (username,bank,amount,balance,addtime,reason,note,editor) VALUES ('$username','$bank','$amount','$balance','$DT_TIME','$reason','$note','$editor')");
                       
                               $username = $des_r['username'];
                               $bank = $des_r['bank'];
                               $amount = $res['destprice'];
                               $balance = $des_r['money'];
                               $reason = '提供采购赚取';
                               $note = '提供采购赚取'.$res['destprice'];
                               $editor = $des_r['username'];
                               $db->query("INSERT INTO {$DT_PRE}finance_record (username,bank,amount,balance,addtime,reason,note,editor) VALUES ('$username','$bank','$amount','$balance','$DT_TIME','$reason','$note','$editor')");
                               if($result){
                            dmsg("操作成", $forward);
                        }
                    }
                }
             } else{
                   $result = $db->query("update $table set status = {$s_status} where  itemid = {$itemid}");
                   if($result){
                       dmsg("操作成", $forward);
                   }
             }
           
        break;
	default:
		$status = isset($status) ? intval($status) : 3;
		in_array($status, array(1, 2, 3, 4)) or $status = 3;
		$condition = "username='$_username'";
		//$condition .= " AND status=$status";
                if($status==3){
                    $condition .= " AND status in(3,5,8,9,10)";
                }else{
                    $condition .= " AND status=$status";
                }
		$typeid = isset($typeid) ? ($typeid === '' ? -1 : intval($typeid)) : -1;
		if($keyword) $condition .= " AND keyword LIKE '%$keyword%'";
		if($catid) $condition .= ($CAT['child']) ? " AND catid IN (".$CAT['arrchildid'].")" : " AND catid=$catid";
		if($typeid >=0 ) $condition .= " AND typeid=$typeid";
		$timetype = strpos($MOD['order'], 'add') !== false ? 'add' : '';
		$lists = $do->get_list($condition, $MOD['order']);
                foreach ($lists as $key => $value) {
                    $item_id .= $value['itemid'].',';
                  //  $lists['itemid_'.$value['itemid']] = 0;
                }
                if(!empty($item_id)){
                    $item_id = substr($item_id,0,strripos($item_id,","));
                    $sql = "SELECT COUNT(id)  total,buy_6_id FROM {$DT_PRE}purchase_price WHERE buy_6_id IN($item_id) GROUP BY buy_6_id";
                    $result = $db->query($sql);
                    $resu_ = Array();
                    while($r = $db->fetch_array($result)) {
                      $resu_[$r['buy_6_id']] = $r['total'];
                    }
                }
             //   $r = $db->get_one("SELECT COUNT(*) AS num FROM {$table} WHERE username='$_username' AND status=$i");
        
	break;
}
if($_userid) {
	$nums = array();
	for($i = 1; $i < 5; $i++) {
		$r = $db->get_one("SELECT COUNT(*) AS num FROM {$table} WHERE username='$_username' AND status=$i");
		$nums[$i] = $r['num'];
	}
}
$head_title = lang($L['module_manage'], array($MOD['name']));
include template($MOD['template_my'] ? $MOD['template_my'] : 'my_'.$module, 'member');
?>